/***
  *@info app与web交互方法,采用javascriptCore方式
  *@author: thinkmix
  *@date 2017-12-27
***/
import './base64';

!function (a, b) {
  "function" == typeof define && (define.amd || define.cmd) ? define(function () {
    return b(a)
  }) : b(a);
}(window, function (a) {
  var URL = getLocalPath(),
    ORIGIN = getOrigin(),
    OS_TYPE = getUserAgent(),
    DEV = process.env.NODE_ENV === 'development'; // 是否是开发模式

  // 获取域名
  function getOrigin () {
    let ret = window.location.origin;

    if (!ret) {
      ret = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
    }

    return ret;
  }
  // 获取url绝对路径
  function getLocalPath () {
    var _url = window.location.href;
    _url = _url.split('.html')[0].split('/');
    _url.splice(_url.length - 1, 1);
    return _url.join('/') + '/';
  }
  // 判断终端类型
  function getUserAgent () {
    let ua = navigator.userAgent.toLowerCase();
    let ret = null;

    if (/android/g.test(ua)) {
      ret = 2;
    } else if (/iphone|mac|ios/g.test(ua)) {
      ret = 1;
    }

    return ret;
  }
  // 生成函数名
  function createFnName () {
    return 'CB_' + Date.now() + '_' + Math.ceil(Math.random() * 10);
  }
  // 判断是否在webView环境中
  function isWebViewEnv () {
    var ua = navigator.userAgent.toLowerCase();
    // if (ua.match(/SELL_CARD_SDK/i) == "SELL_CARD_SDK") {
    //   return true;
    // } else {
    //   return false;
    // }

    return !DEV;
  }
  // 设置url
  function setSourceUrl (url) {
    if (url.indexOf("http") === -1) {
      return URL + url.replace(/.html/g, '.' + APP_SOURCE.appId + '.html');
    } else {
      return url;
    }
  }
  // call app function
  function callHandler (props) {
    let callbackName = createFnName();
    a[callbackName] = function (result) {
      if (result) {
        try {
          //alert(`${props.name},return：${BASE64.decode(result)}`)
          result = JSON.parse(BASE64.decode(result));
          typeof props.callback === 'function' && props.callback(result);
        } catch (error) {
          alert('交互后产生的异常：' + error);
          // alert('交互数据解析错误');
        }
      }
    };

    //alert(`${props.name},call：${JSON.stringify(props.data)}`)
    if (DEV) return;

    if (OS_TYPE == 2) {
      window.webviewBridge.callHandler(props.name, BASE64.encode(JSON.stringify(props.data)), callbackName);
    } else if (OS_TYPE == 1) {
      window.webkit.messageHandlers.callHandler.postMessage({
        name: props.name,
        data: BASE64.encode(JSON.stringify(props.data)),
        callbackName
      })
    }
  }
  a.Jsborya = {
    ready (cb) {
      if (isWebViewEnv()) {
        let num = 0;
        let timer = setInterval(function () {
          num++;

          if (
            (OS_TYPE == 2 && window.webviewBridge) ||
            (OS_TYPE == 1 && window.webkit && window.webkit.messageHandlers)
          ) {
            clearInterval(timer);
            cb();
          } else if (num / 10 > 10) {
            // alert('挂载webviewBridge超时');
            clearInterval(timer);
          }
        }, 100);
      } else setTimeout(function () {
        window.webviewBridge = {
          callHandler () {

          }
        };
        cb();
      }, 300);
    },
    getUserInfo (cb) { // 获取登录用户信息
      if (DEV) {
        cb({
          "applicationID": "EDCF1757-1317-42F7-A5A7-F5A735AE43DB",
          "timestamp": "1591167086714",
          "userPhone": "15821870577",
          "userId": "XU200212182423148502",
          "token": "g8obdB8vyuPjcY+Qd/usQvP4pjIPVM6nSl+VnOzvQnsQrAJlD+zU6ULjZ7RXebqFJ2ZhHTBFR2ibjBvfiC8pGYN2fbhfPC91Bipt8fpta5XtW8BPEQ5rUTYNQifsBm8DB0ClCAWCVk8rKEuhYrOR5Q==",
          "packageName": "com.xingniu.xsk",
          "city": "全国",
          "cityCode": "100"
        })
      }

      callHandler({
        name: 'getUserInfo',
        data: '',
        callback (result) {
          let cityInfo = window.localStorage.getItem('SDK_USER_CITY');

          if (cityInfo) {
            cityInfo = JSON.parse(cityInfo);
          } else {
            cityInfo = {
              cityName: '全国',
              cityCode: '100'
            };
          }

          result.city = cityInfo.cityName;
          result.cityCode = cityInfo.cityCode;

          cb(result);
        }
      });
    },
    webviewLoading (json) { // loading
      callHandler({
        name: 'webViewLoading',
        data: {
          isLoad: json.isLoad
        },
        callback (result) {
          console.log('webviewLoading');
        }
      });
    },
    pageJump (json) { // 页面跳转
      json.url = setSourceUrl(json.url);
      if (!json.hasOwnProperty('destroyed')) json.destroyed = false; // 默认是不销毁当前视图
      if (!json.hasOwnProperty('apiComplete')) json.apiComplete = ''; // 默认apiComplete为空
      if (isWebViewEnv()) {
        callHandler({
          name: 'pageJump',
          data: json,
          callback (result) {
            console.log('jump');
          }
        });
      } else {
        // if (json.data && json.data.subUrl) {
        //   window.location.href = json.data.subUrl;
        // } else if (json.url) {
        //   window.location.href = json.url;
        // }

      }

    },
    pageBack (json) { // 页面返回
      json.url = setSourceUrl(json.url);

      if (DEV) window.location.href = json.url;

      callHandler({
        name: 'pageBack',
        data: json,
        callback (result) {
          console.log('back');
        }
      });
    },
    pageReload (json) { // 页面重载
      json.url = setSourceUrl(json.url);

      if (DEV) window.location.href = json.url;

      callHandler({
        name: 'pageReload',
        data: json,
        callback (result) {
          console.log('pageReload');
        }
      });
    },
    callCamera (json) { // 调用摄像头
      if (json.request && json.request.url) {
        json.request.url = ORIGIN + json.request.url;
      }

      callHandler({
        name: 'callCamera',
        data: json,
        callback (result) {

        }
      });
    },
    registerMethods (name, cb) { // 注册-提供APP直接调用的方法
      a[name] = function (result) {
        try {
          // alert(name + '获取结果：' + BASE64.decode(result));
          if (result && result != 'null') result = JSON.parse(BASE64.decode(result));
          return cb(result);
        } catch (e) {
          console.log(e);
        }
      };
    },
    setHeader (json) { // 设置头部header
      if (!json.hasOwnProperty('showHeaderBorderBottom')) json.showHeaderBorderBottom = true; // 默认显示title线框

      callHandler({
        name: 'setHeader',
        data: json,
        callback (result) {
          console.log('success');
        }
      });
    },
    freeCache (json) { // 清除APP缓存
      callHandler({
        name: 'freeCache',
        data: json,
        callback (result) {
          console.log('freeCache');
        }
      });
    },
    getAuth (json) { // 获取加密信息
      if (DEV) {


        json.complete({
          boryaAuth: "XU200212182423148502,2020052900,12.4.5,1,14,2128776949939078"
        });
      }

      callHandler({
        name: 'getAuth',
        data: json.data,
        callback (result) {
          json.complete(result);
        }
      });
    },
    faceVerTencent (json) { // 腾讯活体识别
      if (json.request && json.request.url) {
        json.request.url = ORIGIN + json.request.url;
      }

      if (DEV) {
        json.complete({
          status: '',
          msg: '',
          livingImageName: '',
          similarity: '',
        })
      }

      callHandler({
        name: 'faceVerTencent',
        data: json,
        callback (result) {
          json.complete(result);
        }
      });
    },
    faceVerZhenXin (json) { // 真信活体识别
      if (json.request && json.request.url) {
        json.request.url = ORIGIN + json.request.url;
      }

      if (DEV) {
        json.complete({
          status: '',
          msg: '',
        })
      }

      callHandler({
        name: 'faceVerZhenXin',
        data: json,
        callback (result) {
          json.complete(result);
        }
      });
    },
    checkDeviceStatus (cb) { // 读取设备状态
      if (DEV) {
        cb({
          status: 'CONNECTION',
          deviceName: '123456',
        })
      }

      callHandler({
        name: 'checkDeviceStatus',
        data: '',
        callback (result) {
          cb(result);
        }
      });
    },
    readIdCardInfo (json) { // 读取证件信息
      if (json.request && json.request.url) {
        json.request.url = ORIGIN + json.request.url;
      }

      if (DEV) {
        setTimeout(() => {
          json.complete({
            status: 'SUCCESS',
            headImgUrl: '',
            idCardName: 'A',
            idCardNo: '123456789012345678',
            idCardAddress: '四川省成都市',
            idCardPeriod: '2020.01.01-2020.01.01'
          })
        }, 2000)
      }

      callHandler({
        name: 'readIdCardInfo',
        data: json,
        callback (result) {
          json.complete(result);
        }
      });
    },
    readCardICCID (cb) { // 读取iccid
      if (DEV) {
        cb({
          status: 'SUCCESS',
          iccid: '123456'
        })
      }

      callHandler({
        name: 'readCardICCID',
        data: '',
        callback (result) {
          cb(result);
        }
      });
    },
    readCardIMSI (cb) { // 读取imsi
      if (DEV) {
        cb({
          status: 'SUCCESS',
          imsi: '',
          smsp: ''
        })
      }

      callHandler({
        name: 'readCardIMSI',
        data: '',
        callback (result) {
          cb(result);
        }
      });
    },
    callWriteCard (json) { // 写卡
      if (DEV) {
        json.complete({
          status: 'SUCCESS'
        })
      }

      callHandler({
        name: 'callWriteCard',
        data: json,
        callback (result) {
          json.complete(result);
        }
      });
    },
    callScanQRCode (json) { // 扫一扫功能

      callHandler({
        name: 'callScanQRCode',
        data: json,
        callback (result) {

        }
      });
    },
    downloadFile (json) {
      if (DEV) {
        json.complete({
          status: 'SUCCESS'
        })
      }

      callHandler({
        name: 'downloadFile',
        data: json,
        callback (result) {
          json.complete(result);
        }
      });
    },
    getUnreadMessage (cb) { // 获取未读消息
      if (DEV) {
        cb({
          total: 0,
        })
      }

      callHandler({
        name: 'getUnreadMessage',
        data: '',
        callback (result) {
          cb(result);
        }
      });
    },
  };

});